var express = require("express");
var router = express.Router();
var Post = require("../../../../models/Post.ts");
const ObjectConfig = require("../../../../models/ObjectConfig.ts"); //拿到总配置信息。

const BelongIds = {
  POST_BELONGID: "1", //常规发布文章
  MD_BELONGID: "2", //发布MD格式的文章
};

/**
 * 获取所有实体数据。
 */
//@Api(name="/rest/object/json/posts")
router.get("/object/json/posts", (req, res) => {
  try {
    Post.all(function (err, posts) {
      if (err) {
        posts = [];
      }
      let response = {
        code: 200,
        msg: "OK",
        data: posts,
      };
      res.send(response);
    });
  } catch (error) {
    res.send(error);
  }
});

/**增加一条数据信息。
 * 入参
 * @param id 客户id
 */
//@Api(name="/rest/object/open/create")
router.post("/object/open/create", (req, res) => {
  const body = req.body;
  if (
    body.belongId === BelongIds.POST_BELONGID ||
    body.belongId === BelongIds.MD_BELONGID
  ) {
    createPost(req.session.user, body, res);
  }
});

function createPost(user, body, res) {
  var post = null;
  switch (body.belongId) {
    case BelongIds.POST_BELONGID:
      post = new Post(user.name, body.title, body.post, "");
      break;
    case BelongIds.MD_BELONGID:
      post = new Post(user.name, body.title, body.html, body.md);
      break;
    default:
      break;
  }
  post.save(function (err) {
    if (err) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: null,
      });
    } else {
      res.send({
        code: 200,
        msg: "恭喜您！发布成功",
        data: null,
      });
    }
  });
}

/**
 * 删除一条数据信息
 * 入参只有id
 */
//@Api(name="/rest/object/delete")
router.post("/object/delete", (req, res) => {
  const body = req.body;
  if (
    body.belongId === BelongIds.POST_BELONGID ||
    body.belongId === BelongIds.MD_BELONGID
  ) {
    deletePost(body, res);
  }
});

function deletePost(body, res) {
  let ids = body.ids || [];
  Post.delete(ids, function (err) {
    if (err) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: null,
      });
    } else {
      res.send({
        code: 200,
        msg: "恭喜您！删除完毕",
        data: null,
      });
    }
  });
}

/**
 * 打开一条信息
 * 入参只有id
 */
//@Api(name="/rest/object/open/detail")
router.post("/object/open/detail", (req, res) => {
  const body = req.body;
  console.log("[belongId]", body);
  if (
    body.belongId === BelongIds.POST_BELONGID ||
    body.belongId === BelongIds.MD_BELONGID
  ) {
    openPost(body, res);
  }
});

function openPost(body, res) {
  let id = body.id;
  if (!id) {
    res.send({
      code: 201,
      msg: "请检查入参，缺失参数",
      data: null,
    });
  }
  Post.get(id, function (err, result) {
    if (err) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: null,
      });
    } else {
      res.send({
        code: 200,
        msg: "数据返回成功",
        data: result,
      });
    }
  });
}

module.exports = router;
